package web.servlet.userlist.web.servelt;


import org.apache.commons.beanutils.BeanUtils;
import web.servlet.userlist.domin.User;
import web.servlet.userlist.service.UserService;
import web.servlet.userlist.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author: Administrator
 * @Date: 2020/5/28 19:07
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /* 1、设置编码
         *  2、获取用户填写的验证码
         *  3、校验验证码
         *    1）获取session中的内存验证码
         *    2）比较两个验证码是否一致
         *       若不一致，提示信息保存在request域，转发到login.jsp
         *       若一致：
         *          （1）获取用户填写的信息
         *          （2）封装成user对象，利用BeanUtils
         *          （3）调用service的方法，判断是否登录成功
         *               若成功，将用户对象存入session，重定向到index.jsp
         *               若不成功，提示信息保存在request域，转发到login.jsp*/
        String verifycode = req.getParameter("verifycode");
        String checkCode_session = (String) req.getSession().getAttribute("checkCode_session");
        if(verifycode.equalsIgnoreCase(checkCode_session)){
            Map<String, String[]> map = req.getParameterMap();
            User user=new User();
            try {
                BeanUtils.populate(user,map);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            System.out.println(user);
            UserService service=new UserServiceImpl();
            User login = service.login(user);
            if(login!=null){
                req.getSession().setAttribute("user",login);
                resp.sendRedirect(req.getContextPath()+"/userlist/index.jsp");
            }else{
                req.setAttribute("login_msg","用户名或密码错误");
                req.getRequestDispatcher("/userlist/login.jsp").forward(req,resp);
            }
        }else{
            req.setAttribute("login_msg","验证码错误");
            req.getRequestDispatcher("/userlist/login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
